package org.easy.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 用465端口发送邮件
 *
 * @author qiaojun
 * @date 2019/8/12
 */
public class MailUtil {

    public static void main(String[] args) {
        sendMail("2638898550@qq.com", null, "测试标题", "测试内容");
    }

    public static void sendMail(String subject, String content) {
        sendMail(null, null, subject, content);
    }

    public static void sendMail(String to, String subject, String content) {
        sendMail(to, null, subject, content);
    }

    /**
     * 发邮件端口改为465
     *
     * @param to      发送人 逗号分开
     * @param cc      抄送人 逗号分开
     * @param content 发送内容
     */
    public static void sendMail(String to, String cc, String subject, String content) {
        if (null == to) {
            return;
        }
        Properties props = new Properties();
        // 发件人
        String USER_NAME = "zhou_8530@163.com";
        props.put("username", USER_NAME);
        // 密码
        String PASSWORD = "JYCAVUIGSLSPCDCD";
        props.put("password", PASSWORD);

        //网易的smtp服务器地址
        String HOST = "smtp.163.com";
        props.put("mail.smtp.host", HOST);
        //SSLSocketFactory类的端口
        props.put("mail.smtp.socketFactory.port", "465");
        //SSLSocketFactory类
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        //网易提供的ssl加密端口,QQ邮箱也是该端口
        props.put("mail.smtp.port", "465");

        Session defaultInstance = Session.getDefaultInstance(props);
        try {
            Session session = Session.getInstance(props, null);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(props.getProperty("username")));
            if (StringUtils.isEmpty(to)) {
                to = "zhou_8530@163.com";
            }
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            if (cc != null) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
            message.setSubject(subject);
            // 正文和响应头
            message.setContent(content, "text/html;charset=UTF-8");
            message.saveChanges();
            Transport transport = defaultInstance.getTransport("smtp");
            transport.connect(props.getProperty("mail.smtp.host"), props.getProperty("username"), props.getProperty("password"));
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (AddressException e) {
            throw new RuntimeException(e);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
    }
}